package com.br.aiops.listeners;

import com.br.aiops.counter.AlertLogCounter;
import com.br.aiops.counter.Counter;
import com.br.aiops.events.CountEvent;
import com.br.aiops.schedule.AbstractSchedule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class AlertTimesListener extends AbstractListener{

    private static final Logger LOGGER = LoggerFactory.getLogger(AlertTimesListener.class);

    @Autowired
    private Counter counter;

    @EventListener(condition = "#event.getAlertLogCounter().getRule().getJudgeType() == 2")
    public void handlerEvent(CountEvent event) {
        LOGGER.debug("收到事件: {}", event);
        AlertLogCounter alertLogCounter = event.getAlertLogCounter();

        //同时在周期内统计，用于恢复
        AbstractSchedule schedule = getSchedule(alertLogCounter.getRule().getDuration());
        schedule.count(alertLogCounter);

        //阶梯只统计不告警
        if (alertLogCounter.shouldLadderAlert()) {
            return;
        }

        try {
            //保证原子性
            lock.lock();
            // 达到告警次数阈值，则进行告警
            if (alertLogCounter.getAlertTimes().get() >= alertLogCounter.getRule().getTimes()) {
                //发送告警
                alertSender.sendAlertMessage(alertLogCounter);

                //告警次数清零
                counter.getCounter().get(alertLogCounter.counterKey()).getAlertTimes().set(0);
            }
        } finally {
            lock.unlock();
        }
    }
}
